package com.xinshujia.config.authentication.service;

import com.xinshujia.dao.RoleDao;
import com.xinshujia.dao.UserDao;
import com.xinshujia.entity.RoleEntity;
import com.xinshujia.entity.UserEntity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Set;

/**
 * *************************************
 * *   @author: 野狼上校               **
 * *   @since: 2024-07-15 19:42       **
 * *   @version: 1.0                  **
 * *************************************
 * <p>
 */
@Service
public class MyUsernamePasswordDetailsService implements UserDetailsService, UserDetailsPasswordService {
    private final UserDao userDao;
    private final RoleDao roleDao;

    public MyUsernamePasswordDetailsService(UserDao userDao, RoleDao roleDao) {
        this.userDao = userDao;
        this.roleDao = roleDao;
    }

    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        return null;
    }

    /**
     * 根据用户名查询用户
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户
        UserEntity userEntity = userDao.loadUserByUsername(username);
        if(ObjectUtils.isEmpty(userEntity)) throw new UsernameNotFoundException("账号不存在");
        // 根据用户Id查询该用户拥有的角色（roles）
        Set<RoleEntity> roles = roleDao.getRolesByUid(userEntity.getId());
        userEntity.setRoles(roles);
        return userEntity;
    }
}
